#include "Server.h"

#include "Config.h"
#include "IOServicePool.h"

Server::Server(io_context& io_context, const unsigned short port)
    : _acceptor(io_context, ip::tcp::endpoint(tcp::v4(), port)) {
    std::clog << "服务器启动端口 = " << port << std::endl;
}

void Server::StartAccept() {
    auto self = shared_from_this();
    //从io_context池子中取出io_context
    auto& io_context = IOServicePool::GetInstance(Config::GetInstance()._server_pool_size)->GetIOService();
    auto http_con = std::make_shared<HttpConnection>(io_context);
    try {
        _acceptor.async_accept(http_con->GetSocket(), [self, http_con](const boost::system::error_code& ec) {
            //出错则放弃这个连接，继续监听新链接
            if (ec) {
                std::cerr << "连接错误: " << ec.message() << std::endl;
            }
            else {
                http_con->Start();
            }
            self->StartAccept();
        });
    }
    catch (std::exception& e) {
        std::cout << "exception is " << e.what() << std::endl;
        // self->StartAccept();
    }
}
